/*********************************************************************************
 * 文件名称: aliyun_iot_platform_timer.c
 * 作       者:
 * 版       本:
 * 日       期: 2016-05-30
 * 描       述:
 * 其       它:
 * 历       史:
 **********************************************************************************/

#include <stdlib.h>
#include <unistd.h>
#include "aliyun_iot_platform_timer.h"

VOID aliyun_iot_timer_assignment(INT32 millisecond,ALIYUN_IOT_TIME_TYPE_S *timer)
{
    timer->time = (struct timeval){millisecond / 1000, (millisecond % 1000) * 1000};
}

INT32 aliyun_iot_timer_start_clock(ALIYUN_IOT_TIME_TYPE_S *timer)
{
    gettimeofday(&timer->time, NULL);

    return (INT32)SUCCESS_RETURN;
}

INT32 aliyun_iot_timer_spend(ALIYUN_IOT_TIME_TYPE_S *start)
{
    struct timeval now, res;

    gettimeofday(&now, NULL);
    timersub(&now, &start->time, &res);
    return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}

INT32 aliyun_iot_timer_remain(ALIYUN_IOT_TIME_TYPE_S *end)
{
    struct timeval now, res;

    gettimeofday(&now, NULL);
    timersub(&end->time, &now, &res);
    return (res.tv_sec)*1000 + (res.tv_usec)/1000;
}

INT32 aliyun_iot_timer_expired(ALIYUN_IOT_TIME_TYPE_S *timer)
{
    struct timeval now, res;
    gettimeofday(&now, NULL);
    timersub(&timer->time, &now, &res);
    return res.tv_sec < 0 || (res.tv_sec == 0 && res.tv_usec <= 0);
}


VOID aliyun_iot_timer_init(ALIYUN_IOT_TIME_TYPE_S* timer)
{
    timer->time = (struct timeval){0, 0};
}

VOID aliyun_iot_timer_cutdown(ALIYUN_IOT_TIME_TYPE_S* timer,UINT32 millisecond)
{
    struct timeval now;
    gettimeofday(&now, NULL);
    struct timeval interval = {millisecond / 1000, (millisecond % 1000) * 1000};
    timeradd(&now, &interval, &timer->time);
}

UINT32 aliyun_iot_timer_now()
{
    return (UINT32) (time(NULL) * 1000);
}

INT32 aliyun_iot_timer_interval(ALIYUN_IOT_TIME_TYPE_S *start,ALIYUN_IOT_TIME_TYPE_S *end)
{
    return (end->time.tv_sec - start->time.tv_sec)*1000 + (end->time.tv_usec - start->time.tv_usec)/1000;
}
